package com.gykfbxxh.imovie.custom.net;

import android.content.SharedPreferences;
import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
import com.app.utils.util.LogUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.gykfbxxh.imovie.base.bean.DataBean;
import com.gykfbxxh.imovie.config.AppConfigTools;
import com.gykfbxxh.imovie.config.ConfigKey;
import com.gykfbxxh.imovie.manager.AppConfigManager;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

/**
 * 制作一个 Gson的get请求
 * Makes a get request and converts the response from JsonElement into a
 * list of objects/object using with Google Gson.
 * Created by xuxinghai on 2016/6/12.
 */
public class GsonGetRequest<T> extends Request<T>
{
    private final Gson gson;
    private final Type type;
    private final Response.Listener<T> listener;

    /**
     * Make a GET request and return a parsed object from JSON.
     *
     * @param url URL of the request to make
     * @param type is the type of the object to be returned
     * @param listener is the listener for the right answer
     * @param errorListener  is the listener for the wrong answer
     */
    public GsonGetRequest
    (
            @NonNull final String url,
            @NonNull final Type type,
            @NonNull final Gson gson,
            @NonNull final Response.Listener<T> listener,
            @NonNull final Response.ErrorListener errorListener
    )
    {
        super(Method.GET, url, errorListener);

        this.gson = gson;
        this.type = type;
        this.listener = listener;
    }

    @Override
    protected void deliverResponse(T response)
    {
        if(this.listener != null) {
            listener.onResponse(response);
        }
    }

    @Override
    protected Response<T> parseNetworkResponse(NetworkResponse response)
    {

        try
        {

            /**
             * 获取用户Token
             */
            Map<String, String> headers = response.headers;
            String headerValue = headers.get("Set-Cookie");
            if (!TextUtils.isEmpty(headerValue)) {
                String[] tokens = headerValue.split(";");
                for (int i = 0; i < tokens.length; i++) {
                    String token = tokens[i].trim();
                    if (token.equals("no-cache") || token.equals("no-store")) {
                        break;
                    } else if (token.startsWith("mortise_loginToken=")) {
                        try {
                            String tokenStr = token.substring(19);
                            if(!TextUtils.isEmpty(tokenStr)) {
                                LogUtils.e("xuxh","LoginToken="+tokenStr);
                                AppConfigTools.TOKENSTR = tokenStr ;
                                SharedPreferences.Editor editor = AppConfigManager.getInstance().getEditor();
                                editor.putString(ConfigKey.user_token,tokenStr);
                                editor.commit();
                            }
                        } catch (Exception e) {
                        }
                    }
                }
            }
//            String json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            String json = new String(response.data);

            if(TextUtils.isEmpty(json)){
                json = DataBean.getDefaultJson();
            }
            /***
             * 如果解析的json为 空字符串或者null，返回null 执行成功的回调函数
             * 目前json不为空,成功的回调函数返回值不为null
             * 如果解析的json格式不对，执行失败的回调函数
             * 如果type为null执行 失败的回调函数
             */
            return (Response<T>)Response.success
                    (
                            gson.fromJson(json,type),
                            HttpHeaderParser.parseCacheHeaders(response)
                    );
        }
//        catch (UnsupportedEncodingException e)
//        {
//            return Response.error(new ParseError(e));
//        }
        catch (JsonSyntaxException e)
        {
            return Response.error(new ParseError(e));
        }
    }


    /**
     * header
     * @return
     * @throws AuthFailureError
     */
    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String, String> head = new HashMap<>();
        if(TextUtils.isEmpty(AppConfigTools.TOKENSTR)) {
            String tokenStr = AppConfigManager.getInstance().readConfig(ConfigKey.user_token, "");
            if(!TextUtils.isEmpty(tokenStr)) {
                head.put("Cookie","mortise_loginToken="+tokenStr);
            }
        }else {
            head.put("Cookie","mortise_loginToken="+AppConfigTools.TOKENSTR);
        }
        return head;
    }
}
